package ytdp.careagle.com.ytdp.myview;

import android.content.Context;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.FrameLayout;

/**
 * Created by lida on 2017/7/28 0028.
 */

public class MyFrameLayout extends FrameLayout {

    private int mLastXIntercept;
    private int mLastYIntercept;
    private ScrollListener scrollListener;
    private float lastTouthX;
    private float x;

    public MyFrameLayout(@NonNull Context context) {
        this(context, null);
    }

    public MyFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {

    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        boolean intercepted = false;
        int x = (int) event.getX();
        int y = (int) event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN://必须返回false  反正事件无法传递到子布局
                intercepted = false;
                break;
            case MotionEvent.ACTION_MOVE:
                //如果横向滚动大于纵向滚动  那就拦截   反正不拦截
                if (Math.abs(x - mLastXIntercept) > Math.abs(y - mLastYIntercept)) {
                    intercepted = true;
                } else {
                    intercepted = false;
                }
                break;
            case MotionEvent.ACTION_UP://必须返回false  反正事件无法传递到子布局
                intercepted = false;
                break;
            default:
                break;
        }

        mLastXIntercept = x;
        mLastYIntercept = y;
        return intercepted;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        x = event.getX();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastTouthX = x;
                break;
            case MotionEvent.ACTION_UP:
                lastTouthX = 0;
                scrollListener.up();
                break;
            case MotionEvent.ACTION_MOVE:
                float dx = x - lastTouthX;
                if (scrollListener != null && lastTouthX != 0) {
                    scrollListener.scroll(dx * 0.5f);
                }
                lastTouthX = x;
                break;
        }
        return super.onTouchEvent(event);
    }


    public void setScrollListener(ScrollListener scrollListener) {
        this.scrollListener = scrollListener;
    }

    public interface ScrollListener {
        void scroll(float dx);

        void up();
    }
}
